"""
通知系统序列化器
"""
from rest_framework import serializers
from accounts.models import User
from .models import Notification, NotificationTemplate, NotificationSettings


class NotificationSerializer(serializers.ModelSerializer):
    """通知序列化器"""
    sender_name = serializers.CharField(source='sender.username', read_only=True)
    sender_role = serializers.CharField(source='sender.role', read_only=True)
    recipient_name = serializers.CharField(source='recipient.username', read_only=True)
    
    class Meta:
        model = Notification
        fields = [
            'id', 'notification_type', 'title', 'content', 'priority',
            'sender', 'sender_name', 'sender_role',
            'recipient', 'recipient_name',
            'related_object_type', 'related_object_id',
            'is_read', 'read_at', 'is_sent', 'sent_at', 'created_at'
        ]
        read_only_fields = ['id', 'sender', 'recipient', 'created_at', 'sent_at']


class NotificationTemplateSerializer(serializers.ModelSerializer):
    """通知模板序列化器"""
    
    class Meta:
        model = NotificationTemplate
        fields = [
            'id', 'name', 'notification_type', 'title_template', 
            'content_template', 'is_active', 'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at']


class NotificationSettingsSerializer(serializers.ModelSerializer):
    """通知设置序列化器"""
    
    class Meta:
        model = NotificationSettings
        fields = [
            'id', 'user', 'system_notifications', 'resume_notifications',
            'interview_notifications', 'job_notifications', 'email_notifications',
            'email_daily_digest', 'push_notifications', 'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'user', 'created_at', 'updated_at']


class SendNotificationSerializer(serializers.Serializer):
    """发送通知序列化器"""
    recipient_id = serializers.IntegerField(help_text='接收人ID')
    notification_type = serializers.ChoiceField(
        choices=Notification.TYPE_CHOICES,
        help_text='通知类型'
    )
    title = serializers.CharField(max_length=200, help_text='通知标题')
    content = serializers.CharField(help_text='通知内容')
    priority = serializers.ChoiceField(
        choices=Notification.PRIORITY_CHOICES,
        default='normal',
        required=False,
        help_text='优先级'
    )
    related_object_type = serializers.CharField(
        max_length=50,
        required=False,
        allow_blank=True,
        help_text='关联对象类型'
    )
    related_object_id = serializers.IntegerField(
        required=False,
        allow_null=True,
        help_text='关联对象ID'
    )
    
    def validate_recipient_id(self, value):
        """验证接收人ID"""
        try:
            User.objects.get(id=value)
        except User.DoesNotExist:
            raise serializers.ValidationError('接收人不存在')
        return value


class BulkNotificationSerializer(serializers.Serializer):
    """批量发送通知序列化器"""
    recipient_ids = serializers.ListField(
        child=serializers.IntegerField(),
        help_text='接收人ID列表'
    )
    notification_type = serializers.ChoiceField(
        choices=Notification.TYPE_CHOICES,
        help_text='通知类型'
    )
    title = serializers.CharField(max_length=200, help_text='通知标题')
    content = serializers.CharField(help_text='通知内容')
    priority = serializers.ChoiceField(
        choices=Notification.PRIORITY_CHOICES,
        default='normal',
        required=False,
        help_text='优先级'
    )
    related_object_type = serializers.CharField(
        max_length=50,
        required=False,
        allow_blank=True,
        help_text='关联对象类型'
    )
    related_object_id = serializers.IntegerField(
        required=False,
        allow_null=True,
        help_text='关联对象ID'
    )
    
    def validate_recipient_ids(self, value):
        """验证接收人ID列表"""
        if not value:
            raise serializers.ValidationError('接收人列表不能为空')
        
        # 检查所有接收人是否存在
        existing_ids = set(User.objects.filter(id__in=value).values_list('id', flat=True))
        invalid_ids = set(value) - existing_ids
        
        if invalid_ids:
            raise serializers.ValidationError(f'以下接收人ID不存在: {list(invalid_ids)}')
        
        return value


class UserSimpleSerializer(serializers.ModelSerializer):
    """用户简单序列化器（用于通知发送）"""
    full_name = serializers.SerializerMethodField()
    
    class Meta:
        model = User
        fields = ['id', 'username', 'first_name', 'last_name', 'full_name', 'role', 'email']
    
    def get_full_name(self, obj):
        """获取用户全名"""
        if obj.first_name and obj.last_name:
            return f"{obj.first_name}{obj.last_name}"
        return obj.username
